<?php

namespace app\admin\controller\user;

use app\api\controller\Paycall;
use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use function fast\e;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->field('id,nickname,avatar,mobile,money,score,pid,status')
                ->paginate($limit)->each(function ($item, $key) {
                    if (!empty($item['status'])) {
                        $pid = explode(',', $item['pid']);
                        // 是团长：直接去团长的名字 否则 在查上一级
                        $status = Db::name('user')->where('id', $pid[0])->value('status');
                        if ($status == 1) {
                            $item['team'] = Db::name('user')->where('id', $pid[0])->value('nickname');
                            if ($status != 1 && $status != 0) {
                                if (Db::name('user')->where('id', $pid[1])->value('status') == 1) {
                                    $item['team'] = Db::name('user')->where('id', $pid[1])->value('nickname');
                                } else {
                                    $item['team'] = '';
                                }
                            }
                        }
                    } else {
                        $item['team'] = '-';
                    }

                    //获取用户会员卡信息
                    $userCard = Db::name('user_card')->where(['member_id' => $item['id']])->find();
                    if (!$userCard) {
                        $item['vip_card'] = "未开通";
                        $item['vip_card_time'] = "-";
                    } elseif ($userCard['status'] == 0) {
                        $item['vip_card'] = "未领取";
                        $item['vip_card_time'] = date('Y-m-d', $userCard['vip_card_time']);
                    } elseif ($userCard['status'] == 1) {
                        $item['vip_card'] = "已开通";
                        $item['vip_card_time'] = date('Y-m-d', $userCard['vip_card_time']);
                    } else {
                        $item['vip_card'] = "已过期";
                        $item['vip_card_time'] = date('Y-m-d', $userCard['vip_card_time']);
                    }
                    return $item;
                });
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }


    public function setVip()
    {
        $ids = $this->request->post("id");
        $vip_card = Db::name('vip_card')->where(['id' => 1])->find();
        $end_time = time() + $vip_card['day'] * 86400;
        $createCard = (new Paycall())->createVipCard($ids, $end_time, $vip_card['pay_goods_nums']);
        if ($createCard) {
            $this->success();
        }
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }


    /*
     * 返利记录
     */
    public function record($ids)
    {
        $row = $this->model->get(['id' => $ids]);

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = Db::name('user_consume')
            ->where(['user_id' => $ids, 'type' => 3])
            ->where('sub_user_id', '>=', 0)
            ->order('id desc')
//            ->where('status','in','5,6')
//            ->limit($limit)
            ->paginate(10)->each(function ($item, $key) {
                switch ($item['type']) {
                    case 1;
                        $item['type'] = '金额';
                        break;
                    case 2;
                        $item['type'] = '积分';
                        break;
                    case 3;
                        $item['type'] = '提成';
                        break;
                }
                if ($item['content'] == '返利' || $item['content'] == '金额返利') {
                    $item['content'] = '提成';
                }
                $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                return $item;
            });

        $this->view->assign("row", $list);
        return $this->view->fetch();
    }


    /*
     * 金额记录
     */
    public function recordMoney($ids)
    {
        $row = $this->model->get(['id' => $ids]);

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $where = [
            'user_id' => $ids,
            'state' => 1,
        ];
        //购买记录
        $list = Db::name('user_consume')
            ->where($where)
            ->order('id desc')
            ->paginate(10, false, ['query' => request()->param()])->each(function ($item, $key) {
                $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                $item['type_name'] = '购买商品';
                switch ($item['type']) {
                    case 1;
                        $item['type_content'] = '余额消费';
                        break;
                    case 2;
                        $item['type_content'] = '爱心值消费';
                        break;
                    case 4;
                        $item['type_content'] = '微信支付';
                        break;
                }
                return $item;
            });
        $this->view->assign("row", $list);
        return $this->view->fetch();
    }


    /*
     * 积分记录
     */
    public function recordInt($ids)
    {
        $row = $this->model->get(['id' => $ids]);

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = Db::name('user_consume')
            ->where('user_id', $ids)
            ->where('type', 2)
            ->order('id desc')
            ->paginate(10)->each(function ($item, $key) {
                switch ($item['type']) {
                    case 1;
                        $item['type'] = '金额';
                        break;
                    case 2;
                        $item['type'] = '积分';
                        break;
                    case 3;
                        $item['type'] = '返利';
                        break;
                }
                if ($item['status'] == 1) {
                    $item['money'] = '+' . $item['money'];
                } else {
                    $item['money'] = '-' . $item['money'];
                }
                $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                return $item;
            });

        $this->view->assign("row", $list);
        return $this->view->fetch();
    }

    /*
     *  审核改为团长
     * */
    public function change($ids)
    {
        $user = Db::name('user')->where('id', $ids)->find();
        if (empty($user['status'])) {
            // if(!empty($user['pid']))$this->error(__('他有上级,不能设置为团长'));
            $res = Db::name('user')->where('id', $ids)->update(['status' => 1, 'pid' => 0]);
        } else {
            $res = Db::name('user')->where('id', $ids)->update(['status' => 0]);
            Db::name('user')->where('pid', $ids)->update(['pid' => 0]);
        }
        if ($res) {
            $this->success();
        } else {
            $this->error(__('审核失败'));
        }
    }


}
